<?php
class Updater{
	
	var $paths = array(TABLES);
	
	function __construct(){
		//Read file path, find files , include run the update function ... ( check if uses extends )
		$updateInfoArr = array();
		
		foreach($this->paths as $path){
			if ($handle = opendir($path)) {
				while (false !== ($file = readdir($handle))) {
					if ($file != "." && $file != ".." && strpos($file, '.php') !== false ) {
						$className = str_replace('.php', '', $file);
						
						if( strpos( $className, '_' ) === 0 ){
							include_once($path.'/'.$file);
							$class = new $className();
							$classConstruct = $class->__construct(); //double call construct, because its a hack to help update
							$updateInfoArr[$className] = $this->update($classConstruct);
						}
          }
        }
        closedir($handle);
      }
		}
		
		$isDependantOn = array();
		if( $updateInfoArr ){
			foreach($updateInfoArr as $table=>$updateInfo){
				foreach($updateInfo as $info){
					if( $info['dependantOn'] ){
						foreach($info['dependantOn'] as $dependantOn){
							//TODO:: Do column cross checking 
							//TODO:: Need to check if the table that is being added has dependants 
							$isDependantOn[] = $dependantOn['table'];
						}
					}
				}
			}
		}
		
		$sqlArray = array();
		if( $updateInfoArr ){
			foreach($updateInfoArr as $table=>$updateInfo){
				foreach($updateInfo as $info){
					if( in_array($table, $isDependantOn)){
						array_unshift($sqlArray,$info['sql'] );
					}else{
						$sqlArray[] = $info['sql'];
					}
				}
			}
		}
		
		
		foreach($sqlArray as $sql){
			$db = F::get()->DB();
			if( $sql ){
				foreach($sql as $val){
					F::get()->Tpl()->addMessage('Updater',$val);
					$db->query( $val );
				}
			}
		}
	}
	
	
	function update($loaderObject) {
		$db = F::get()->DB();
		$tbl = $db->describeTable($loaderObject->loader_tableName);
		$updateInfo = array();
		
		$datatypeTable = new DatatypeTable($loaderObject->loader_tableName);
		
		if ($tbl !== false) { //Check for alter tables
			foreach ($loaderObject->loader_variables as $columnName => $variableInfo) {
				if (!isset($tbl[$columnName])) { // Needs to be updates
					$datatype = F::get()->Datatype($columnName, $variableInfo['datatype'], $variableInfo['defaultValue'], $variableInfo['join'], $variableInfo['index'], $variableInfo['length'], $variableInfo['allowNULL']);
					$updateInfo[] = $datatypeTable->getAlterSQL( $datatype );
				}
			}
			
			//TODO wont return the above
			//Columns to drop
			foreach($tbl as $columnName=>$columnInfo){
				if( !isset( $loaderObject->loader_variables[$columnName] ) ){
					$sql = "
					SELECT referenced_table_name, referenced_column_name
					
					FROM INFORMATION_SCHEMA.key_column_usage 
					WHERE referenced_table_schema = '".DB_NAME."' 
					AND referenced_table_name IS NOT NULL 
					AND table_name = '".$loaderObject->loader_tableName."'
					AND `column_name` = '".$columnName."'
					ORDER BY table_name, column_name;";
					
					$relationship = $db->getSingleArray( $sql );
					
					$join = array();
					
					if( $relationship ){
						$join = array('table' => $relationship['referenced_table_name'], 'column' => $relationship['referenced_column_name']);
					}
					
					
					$datatype = F::get()->Datatype($columnName, 'Default', '', $join );
					$updateInfo[] = $datatypeTable->getDropSQL( $datatype );
				}
			}
			
		} else {//Update tables
			$datatypesArray = array();
			foreach ($loaderObject->loader_variables as $columnName => $variableInfo) {
				$datatypesArray[] = F::get()->Datatype($columnName, $variableInfo['datatype'], $variableInfo['defaultValue'], $variableInfo['join'], $variableInfo['index'], $variableInfo['length'], $variableInfo['allowNULL']);
			}
			$updateInfo[] =  $datatypeTable->getCreateTableSQL($datatypesArray);
		}
		
		return $updateInfo;
	}
	
}

?>
